package com.feiyisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feiyisys.dto.ActivityDTO;
import com.feiyisys.dto.ActivityResponseDTO;
import com.feiyisys.entity.Activity;
import com.feiyisys.handlers.BaseContext;
import com.feiyisys.mapper.ActivityMapper;
import com.feiyisys.service.ActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 文化遗产相关活动表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Override
    public IPage<ActivityResponseDTO> getActivityPage(Long current, Long size) {
        Page<Activity> page = new Page<>(current, size);
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Activity::getUpdateTime);

        IPage<Activity> activityPage = this.page(page, wrapper);

        return activityPage.convert(this::convertToResponseDTO);
    }

    @Override
    public ActivityResponseDTO getActivityById(Long id) {
        Activity activity = this.getById(id);
        Assert.notNull(activity, "活动不存在");
        return convertToResponseDTO(activity);
    }

    @Override
    public Activity createActivity(ActivityDTO activityDTO) {
        // 验证必填字段
        if (activityDTO.getTitle() == null || activityDTO.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("活动标题不能为空");
        }
        
        // 如果没有提供时间，设置默认值
        Date now = new Date();
        Date defaultEndTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 一周后
        
        Long creatorId = BaseContext.getCurrentId();
        if (creatorId == null) {
            throw new IllegalStateException("管理员信息失效，请重新登录后再尝试创建活动");
        }

        Activity activity = new Activity();
        activity.setTitle(activityDTO.getTitle());
        activity.setCoverImage(activityDTO.getCoverImage());
        activity.setContent(Objects.requireNonNullElse(activityDTO.getContent(), ""));
        activity.setStartTime(Objects.requireNonNullElse(activityDTO.getStartTime(), now));
        activity.setEndTime(Objects.requireNonNullElse(activityDTO.getEndTime(), defaultEndTime));
        activity.setLocation(Objects.requireNonNullElse(activityDTO.getLocation(), "默认地点"));
        activity.setQuota(Objects.requireNonNullElse(activityDTO.getQuota(), 10)); // 默认配额10人
        activity.setStatus(activityDTO.getStatus() != null ? activityDTO.getStatus() : (byte) 1); // 默认状态为报名中
        activity.setCurrentParticipants(0);
        activity.setCreateTime(now);
        activity.setUpdateTime(now);
        activity.setCreatorId(creatorId);

        this.save(activity);
        return activity;
    }


    @Override
    public Activity updateActivity(ActivityDTO activityDTO) {
        Activity activity = this.getById(activityDTO.getId());
        Assert.notNull(activity, "活动不存在");

        // 验证必填字段
        if (activityDTO.getTitle() == null || activityDTO.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("活动标题不能为空");
        }
        
        activity.setTitle(activityDTO.getTitle());
        activity.setCoverImage(activityDTO.getCoverImage());
        activity.setContent(Objects.requireNonNullElse(activityDTO.getContent(), ""));
        activity.setStartTime(activityDTO.getStartTime()); // 更新时不强制设置默认值，保持原逻辑
        activity.setEndTime(activityDTO.getEndTime());
        activity.setLocation(Objects.requireNonNullElse(activityDTO.getLocation(), "默认地点"));
        activity.setQuota(Objects.requireNonNullElse(activityDTO.getQuota(), 10));
        activity.setStatus(activityDTO.getStatus());
        activity.setUpdateTime(new Date());

        // 检查活动是否过期，如果过期自动更新状态
        if (activity.isExpired() && activity.getStatus() != 3) {
            activity.setStatus((byte) 3); // 设置为已结束状态
        }

        this.updateById(activity);
        return activity;
    }

    @Override
    public boolean updateActivityStatus(Long id, Byte status) {
        Activity activity = this.getById(id);
        Assert.notNull(activity, "活动不存在");

        activity.setStatus(status);
        activity.setUpdateTime(new Date());

        return this.updateById(activity);
    }

    /**
     * 转换为响应DTO
     */
    private ActivityResponseDTO convertToResponseDTO(Activity activity) {
        ActivityResponseDTO dto = new ActivityResponseDTO();
        dto.setId(activity.getId());
        dto.setTitle(activity.getTitle());
        dto.setCoverImage(activity.getCoverImage());
        dto.setContent(activity.getContent());
        dto.setStartTime(activity.getStartTime());
        dto.setEndTime(activity.getEndTime());
        dto.setLocation(activity.getLocation());
        dto.setQuota(activity.getQuota());
        dto.setCurrentParticipants(activity.getCurrentParticipants());
        dto.setStatus(activity.getStatus());
        dto.setStatusText(getStatusText(activity.getStatus()));
        dto.setExpired(activity.isExpired()); // 设置过期状态
        dto.setCanRegister(activity.canRegister()); // 设置是否可报名
        dto.setCreateTime(activity.getCreateTime());
        dto.setUpdateTime(activity.getUpdateTime());
        dto.setCreatorId(activity.getCreatorId());
        return dto;
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Byte status) {
        switch (status) {
            case 0: return "下架";
            case 1: return "报名中";
            case 2: return "审核中";
            case 3: return "已结束";
            default: return "未知";
        }
    }
}
